package com.lge.clock.timer;

import java.util.Calendar;
import java.util.Date;

import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.widget.Toast;
//import android.os.SystemProperties;

import com.lge.clock.R;
import com.lge.clock.TimerFragment;
import com.lge.clock.alarmclock.AlarmAlertWakeLock;
import com.lge.clock.alarmclock.Alarms;
import com.lge.clock.stopwatch.StopWatchDBAdapter;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.Log;

/**
 * @author LGE Cappuccino
 */
public class TimerReceiver extends BroadcastReceiver 
{	
	private static final String TAG = "TimerReceiver";
	
	private static final int TIMER_NOTI_ID = 1004;
	private TelephonyManager mTelephonyManager;
	
	private Vibrator vibrator;
	
	private static final int STOPSIGN = 1008;
	/**
	 * Method onReceive.
	 * @param context Context
	 * @param intent Intent
	 */
	@Override
	public void onReceive(Context context, Intent intent) 
	{
		///////////Camera & Voice Recoring??  ??? ?? ????~~~~~~///////////////
        boolean voice_video_playing_YN = false ;
        SharedPreferences prefs = context.getSharedPreferences("VOICE_VIDEO_RECORD_PLAYING", 0);
        SharedPreferences.Editor ed = prefs.edit();
        int play_stateYN = prefs.getInt("PLAY_STATE", 0);
		SharedPreferences mSPref_timer = context.getSharedPreferences("TIMER_STATE", 0);
		SharedPreferences mSPref_stopwatch = context.getSharedPreferences("STOPWATCH_STATE", 0);
				
		//[suhaeng.lee][2884] 2012.01.03 START
		boolean isTimerRunning = mSPref_timer.getBoolean("running", false);
		
        if (isTimerRunning && Alarms.ALARM_ALERT_ACTION.equals(intent.getAction())) {
        	////////////Notification above Timer bottom Time is up and currenttime///////////
        	Calendar cal = Calendar.getInstance();
        	cal.setTimeInMillis(System.currentTimeMillis());
        	boolean is24Hours = android.text.format.DateFormat.is24HourFormat(context);
        	String format = is24Hours ? "kk:mm" : "hh:mm AA";
        	String timeText = " ("+(String)DateFormat.format(format, cal)+")";   	      	

        	NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        	nm.cancel(TIMER_NOTI_ID);
    		Notification noti = new Notification(R.drawable.stat_notify_alarm, context.getText(R.string.superclock_timer).toString(), System.currentTimeMillis());
    		noti.flags |= Notification.FLAG_AUTO_CANCEL;
    		noti.flags |= Notification.FLAG_SHOW_LIGHTS;
    		noti.flags |= Notification.DEFAULT_LIGHTS;
//    		noti.ledARGB = 0xFF00FF00;
//    		noti.ledOnMS = 500;
//    		noti.ledOffMS = 500;
    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    		noti.setLatestEventInfo(context, context.getText(R.string.superclock_timer).toString(), context.getText(R.string.timer_done).toString() + timeText, contentIntent);
    		nm.notify(TIMER_NOTI_ID, noti);
    		////////////Notification above Timer bottom Time is up and currenttime///////////
    		return;
        } 
        //[suhaeng.lee][2884] 2012.01.03 END
        
		//added by essin@lge.com 2011-03-21
        
        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        //added by essin@lge.com 2011-04-04
        //check by AlarmAlert
        if ( intent.getAction().equals("com.lge.clock.alarmclock"))
        {
        	return;
        }
        if(intent.getAction().equals("com.lge.clock.alarmstop"))
        {
        	return;
        }
        //added by essin@lge.com 2011-04-04
        //check by AlarmAlert
        
		// [mo2sangbong.lee@lge.com][20291] 2011.08.11. add timer alarm power off issue fix START
//		if (Intent.ACTION_REQUEST_SHUTDOWN.equalsIgnoreCase(intent.getAction()) ||  
        if (Intent.ACTION_SHUTDOWN.equalsIgnoreCase(intent.getAction()) )
		{
			if ( TimerAlarm.getTimerAlarm() != null) {
				Log.e(TAG,"Timer Alarm recived power off intent then call forceStop");       		
				TimerAlarm.getTimerAlarm().forceStop();
			}			
			Intent timerKilled = new Intent(Timers.TIMER_KILLED);
        	context.sendBroadcast(timerKilled);
			AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
			Intent mIntent = new Intent(Timers.TIMER_ALERT_ACTION);
			PendingIntent sender = PendingIntent.getBroadcast(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
			if(am != null)
			{
				am.cancel(sender);
				am = null;
			}
		}
		// [mo2sangbong.lee@lge.com][20291] 2011.08.11. add timer alarm power off issue fix END
//        if (Intent.ACTION_REQUEST_SHUTDOWN.equalsIgnoreCase(intent.getAction()) ||  
        if (Intent.ACTION_SHUTDOWN.equalsIgnoreCase(intent.getAction()) || 
         	   "android.intent.action.BOOT_COMPLETED".equalsIgnoreCase(intent.getAction())) 
        {        	
        	mSPref_timer.edit().putBoolean("timerstarted", false).commit();
      		mSPref_timer.edit().putLong("endtime", 0L).commit();
         	//StopWatch kill
        	
         	mSPref_stopwatch.edit().putInt("stopwatchstarted", 0).commit();
         	mSPref_stopwatch.edit().putLong("starttime", 0L).commit();
         	mSPref_stopwatch.edit().putLong("endtime", 0L).commit();
         	
         	Log.e(TAG,"stopwatchstarted : " + mSPref_stopwatch.getInt("stopwatchstarted", -1));
         	Log.e(TAG,"starttime : " + mSPref_stopwatch.getLong("starttime", -1L));
         	Log.e(TAG,"endtime : " + mSPref_stopwatch.getLong("endtime", -1L));
         	return;
        }
        if (play_stateYN == 1) {
        	voice_video_playing_YN = true;
        }
        else {
        	voice_video_playing_YN = false;
        }
		/**
         *  recording start action
         */
        if ("voice_video_record_playing".equalsIgnoreCase(intent.getAction())) 
        {//begin 
        	ed.putInt("PLAY_STATE", 1);
        	ed.commit();            
        	  
        	voice_video_playing_YN = true;
        	return;	
    	}//end
          
        /**
         *  recording stop action
         */
        if ("voice_video_record_finish".equalsIgnoreCase(intent.getAction())) 
        {//begin 
        	if (play_stateYN == 0) 
        	{
        		return;  
        	}   
			ed.putInt("PLAY_STATE", 0);
        	ed.commit();
        	voice_video_playing_YN = false;
           	//WakeAlarms(context); //not delay alarm!  
        	return;
        }//...end
        
        final String mHDVTStatus = "2";//SystemProperties.get("net.ims.vt.incall");
        
        /*[START] 2012.03.05 suein1209.kim VT Call State issue*/
        SharedPreferences mVtCallPrefs = context.getSharedPreferences("VT_CALL_IN_OR_OUT_STATE", 0);
        /*[END] 2012.03.05 suein1209.kim VT Call State issue*/
        
        if(voice_video_playing_YN == true)
        {
			//[mo2sangbong.lee][1677] 2011.11.03 START
        	Intent timerKilled = new Intent(Timers.TIMER_KILLED);
        	context.sendBroadcast(timerKilled);
			//[mo2sangbong.lee][1677] 2011.11.03 END
        	Toast.makeText(context, R.string.timer_done, Toast.LENGTH_LONG).show();
        	//////////// Notification above Timer bottom Time is up and currenttime///////////
        	//[suhaeng.lee][2687] show time in Time is up Popup START
        	Calendar cal = Calendar.getInstance();
        	cal.setTimeInMillis(System.currentTimeMillis());
        	boolean is24Hours = android.text.format.DateFormat.is24HourFormat(context);
        	String format = is24Hours ? "kk:mm" : "hh:mm AA";
        	String timeText = " ("+(String)DateFormat.format(format, cal)+")";   	      	
    		//[suhaeng.lee][2687] show time in Time is up Popup END
        	NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        	nm.cancel(TIMER_NOTI_ID);
    		Notification noti = new Notification(R.drawable.stat_notify_alarm, context.getText(R.string.superclock_timer).toString(), System.currentTimeMillis());
    		noti.flags |= Notification.FLAG_AUTO_CANCEL;
    		noti.flags |= Notification.FLAG_SHOW_LIGHTS;
    		noti.flags |= Notification.DEFAULT_LIGHTS;
//    		noti.ledARGB = 0xFF00FF00;
//    		noti.ledOnMS = 500;
//    		noti.ledOffMS = 500;
    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    		noti.setLatestEventInfo(context, context.getText(R.string.superclock_timer).toString(), context.getText(R.string.timer_done).toString() + timeText, contentIntent);
    		nm.notify(TIMER_NOTI_ID, noti);
    		////////////Notification above Timer bottom Time is up and currenttime///////////
        }
        /*[START] 2012.04.04 suein1209.kim*/
//        else if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)
        /*[END] 2012.04.04 suein1209.kim*/
        else if (CommonUtil.isCallStateIdle(mTelephonyManager, context) == false)
		{
			//[mo2sangbong.lee][1677] 2011.11.03 START
        	Intent timerKilled = new Intent(Timers.TIMER_KILLED);
        	context.sendBroadcast(timerKilled);
			//[mo2sangbong.lee][1677] 2011.11.03 END
        	Toast.makeText(context, R.string.timer_done, Toast.LENGTH_LONG).show();
        	
        	//[suhaeng.lee][#50750] 20110906 to vibrate in call state
    		vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
        	vibrator.vibrate(new long[] { 130, 220 }, 0);
        	mVibHandler.sendMessageDelayed(mVibHandler.obtainMessage(STOPSIGN), 800);
        	
        	
        	////////////Notification above Timer bottom Time is up and currenttime///////////
        	//[suhaeng.lee][2687] show time in Time is up Popup START
        	Calendar cal = Calendar.getInstance();
        	cal.setTimeInMillis(System.currentTimeMillis());
        	boolean is24Hours = android.text.format.DateFormat.is24HourFormat(context);
        	String format = is24Hours ? "kk:mm" : "hh:mm AA";
        	String timeText = " ("+(String)DateFormat.format(format, cal)+")";   	      	
    		//[suhaeng.lee][2687] show time in Time is up Popup END
        	NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        	nm.cancel(TIMER_NOTI_ID);
    		Notification noti = new Notification(R.drawable.stat_notify_alarm, context.getText(R.string.superclock_timer).toString(), System.currentTimeMillis());
    		noti.flags |= Notification.FLAG_AUTO_CANCEL;
    		noti.flags |= Notification.FLAG_SHOW_LIGHTS;
    		noti.flags |= Notification.DEFAULT_LIGHTS;
//    		noti.ledARGB = 0xFF00FF00;
//    		noti.ledOnMS = 500;
//    		noti.ledOffMS = 500;
    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    		noti.setLatestEventInfo(context, context.getText(R.string.superclock_timer).toString(), context.getText(R.string.timer_done).toString()+timeText, contentIntent);
    		nm.notify(TIMER_NOTI_ID, noti);
    		////////////Notification above Timer bottom Time is up and currenttime///////////
        }
//        else if (mHDVTStatus != null && "1".equals(mHDVTStatus)) {
        else if (mVtCallPrefs.getBoolean("VTCALL_IN_STATE", false)) {
        	Intent timerKilled = new Intent(Timers.TIMER_KILLED);
        	context.sendBroadcast(timerKilled);
        	Toast.makeText(context, R.string.timer_done, Toast.LENGTH_LONG).show();

        	Log.d(TAG, "========= HDVT Call is incall status =======");
        	////////////Notification above Timer bottom Time is up and currenttime///////////
        	NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        	nm.cancel(TIMER_NOTI_ID);
    		Notification noti = new Notification(R.drawable.stat_notify_alarm, context.getText(R.string.superclock_timer).toString(), System.currentTimeMillis());
    		noti.flags |= Notification.FLAG_AUTO_CANCEL;
    		noti.flags |= Notification.FLAG_SHOW_LIGHTS;
    		noti.flags |= Notification.DEFAULT_LIGHTS;
//    		noti.ledARGB = 0xFF00FF00;
//    		noti.ledOnMS = 500;
//    		noti.ledOffMS = 500;
    		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    		noti.setLatestEventInfo(context, context.getText(R.string.superclock_timer).toString(), context.getText(R.string.timer_done).toString(), contentIntent);
    		nm.notify(TIMER_NOTI_ID, noti);
    		////////////Notification above Timer bottom Time is up and currenttime///////////        	
        }
        else
        {
        	//AlarmAlertWakeLock.acquireCpuWakeLock(context); //[hyunjung78.park][1427] 2011.10.13
			TimerWakeLock.acquireCpuWakeLock(context); //[hyunjung78.park][1427] 2011.10.13

        	TimerWakeLock.acquireScreenWakeLock(context); //[suhaeng.lee][1410] 2011.10.21
        	
        	//[mo2sangbong.lee][1383] 2011.11.07 START
			SharedPreferences mSharedPreferences = context.getSharedPreferences("TIMER_STATE", 0);
			SharedPreferences.Editor mEditor = mSharedPreferences.edit();	
			mEditor.putBoolean("timerstarted", false);
			mEditor.putLong("endtime", 0L);
			mEditor.commit();
			//[mo2sangbong.lee][1383] 2011.11.07 END
    			
        	@SuppressWarnings("rawtypes")
        	
			Class c = TimerFullDialog.class;
    	        
			// TODO Auto-generated method stub
			Intent mIntent = new Intent(context, c);
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			context.startActivity(mIntent);
			
    	}
	}
	
	//[suhaeng.lee][SE#50750] 20110906 to vibrate in call state
    private final Handler mVibHandler = new Handler() {
	    public void handleMessage(Message msg) {
	    	switch (msg.what) 
	    	{
	    		case STOPSIGN :
	    			if (vibrator != null)
	    				vibrator.cancel();
	    			break;
	    			
	    		default :
	    			break;
	    	}
	    }
	};
}
